package week_five;

public class BestTimeToBuySellStock_122 {
    public int maxProfit(int[] prices) {
        //贪心：怎么判断局部最优，全局最优。
        //往后看一天:
        // x ---- y  如果y上涨，不卖，或者买入x
        //   \
        //    --- y  如果y下降或持平，卖出x
        int res = 0;
        int stock = -1;
        for (int i = 0; i < prices.length; i++) {
            int x = prices[i];
            if (i == prices.length - 1) {
                if (stock > -1)
                    res += (x - stock);
                break;
            }
            int y = prices[i + 1];
            if (x < y) {
                // System.out.println("i and i+1: "+ x +", " +y);
                if (stock == -1) {
                    stock = x;
                }
                // System.out.println("stock: "+ stock);
            } else {
                if (stock > -1) {
                    res += (x - stock);
                    stock = -1;
                    // System.out.println("卖出 stock: "+ res);
                }
            }
        }

        return res;

    }
}
